package sjsu.android;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import dbAdapter.DailyInfoDBAdapter1;
import dbAdapter.ProfileDBAdapter;
import android.app.Activity;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
//import android.view.ContextMenu;
//import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
//import android.view.Window;
import android.widget.ProgressBar;
//import android.os.Handler;
//import android.os.Message;

public class CustomListView extends ExpandableListActivity {
    /** Called when the activity is first created. */
	SimpleExpandableListAdapter expListAdapter;
	static final String colors[] = {
		  "Today's my intake",
			};
	static  String [][] shades1;
	static int id = 0;
	public static int caloriesConsumed ;
	public static TextView textViewCal;
	static DailyInfoDBAdapter1 di;
	ProfileDBAdapter db;
	//DailyInfoDBAdapter1 ddb;
	static String categoryName;
	private ListView l1;
	private static final int advancedId = Menu.FIRST;
    private static final int addToProfileId = Menu.FIRST + 1;
    private static final int fitnessId = Menu.FIRST + 2;
    private String[] items=null;
    int lowCal = 0,medCal = 0,highCal = 0;
    int totalcal = 0;
    int ctr = 0;
    int avg =0;
  //  public static ProgressBar pb;
    public static ProgressBar myProgressBar;
    int myProgress = 0;
    int val=0;
    Button save,adv_cat;
	private  class EfficientAdapter extends BaseAdapter {
			 private LayoutInflater mInflater;
			
			 
			 public EfficientAdapter(Context context) {
			 mInflater = LayoutInflater.from(context);
			 
			 }
			 
			 public int getCount() {
			 return Meal.length;
			 }
			 
			 public Object getItem(int position) {
			 return position;
			 }
			 
			 public long getItemId(int position) {
			 return position;
			 }
			 
			 public View getView(int position, View convertView, ViewGroup parent) {
				 ViewHolder holder;
				 if (convertView == null) {
					 convertView = mInflater.inflate(R.layout.listview, null);
					 holder = new ViewHolder();
					 holder.text = (TextView) convertView.findViewById(R.id.TextView01);
					 holder.low = (Button)convertView.findViewById(R.id.Button01);
					 holder.med = (Button)convertView.findViewById(R.id.Button02);
					 holder.high = (Button)convertView.findViewById(R.id.Button03);
					 
					 holder.low.setOnClickListener(new View.OnClickListener() {
						 public void onClick(View v) {
							 System.out.println("begin low");
							 String t = ""+ v.getTag();
							 System.out.println("At low"+t);
					          int tag = new Integer(t);
				//	          holder.low.setBackgroundResource(R.drawable.zen_button_red);
					          
					    //      System.out.println("At low"+tag);
					          lowButtonClicked(tag);
					 }});
				
					 holder.med.setOnClickListener(new View.OnClickListener() {
						 public void onClick(View v) {
							 String t = ""+ v.getTag();
					          int tag = new Integer(t);
					      //    System.out.println(tag);
							 medButtonClicked(tag);
		             }});
				
					 holder.high.setOnClickListener(new View.OnClickListener() {
						 public void onClick(View v) {
							 String t = ""+ v.getTag();
					          int tag = new Integer(t);
					       //   System.out.println(tag);
							 highButtonClicked(tag);
		             }});
	
					 convertView.setTag(holder);
				 } else {
				 
					 holder = (ViewHolder) convertView.getTag();
				 }
			 
				 holder.text.setText(Meal[position]);
				 holder.low.setTag(position); 
				 holder.med.setTag(position);  
				 holder.high.setTag(position);  
//				 holder.low.setBackgroundResource(R.drawable.zen_button_red);
//				 holder.med.setBackgroundResource(R.drawable.button_yellow);
//				 holder.high.setBackgroundResource(R.drawable.button_red);
				 
				 return convertView;
			 }
			 

			 
			 public void lowButtonClicked(int option){
				 if (option == 0){//breakfast
					 lowCal = 200;
					 categoryName = "Breakfast";
				 }
				 else if (option == 1){//lunch
					 lowCal = 300;
					 categoryName = "Lunch";
				 }
				 else if (option == 2){//snack
					 lowCal = 50;
					 categoryName = "Snack";
				 }
				 else if (option == 3){//dinner
					 lowCal = 300;
					 categoryName = "Dinner";
				 }
				 else if (option == 4){//beverages
					 lowCal = 15;
					 categoryName = "Beverages";
				 }
				 else if (option == 5){//dessert
					 lowCal = 30;
					 categoryName = "Dessert";
				 }
			//	checkCal(lowCal);
				 insertIntoDB(lowCal);
				 updateProgressBar();
				 setExpandableList();
				 updateWhatIate();
			 }
			 
			 public void medButtonClicked(int option){
				 if (option == 0){//breakfast
					 medCal = 300;
					 categoryName = "Breakfast";
				 }
				 else if (option == 1){//lunch
					 medCal = 450;
					 categoryName = "Lunch"; 
				 }
				 else if (option == 2){//snack
					 medCal = 100;
					 categoryName = "Snack";
				 }
				 else if (option == 3){//dinner
					 medCal = 450;
					 categoryName = "Dinner";
				 }
				 else if (option == 4){//beverages
					 medCal = 50;
					 categoryName = "Beverages";
				 }
				 else if (option == 5){//dessert
					 medCal = 75;
					 categoryName = "Dessert";
				 }
				// checkCal(medCal);
				 insertIntoDB(medCal);
				 updateProgressBar();
				 setExpandableList();
				 updateWhatIate();
			 }
			 public void highButtonClicked(int option){
				 if (option == 0){//breakfast
					 highCal = 400;
					 categoryName = "Breakfast";
				 }
				 else if (option == 1){//lunch
					 highCal = 550;
					 categoryName = "Lunch";
				 }
				 else if (option == 2){//snack
					 highCal = 150;
					 categoryName = "Snack";
				 }
				 else if (option == 3){//dinner
					 highCal = 600;
					 categoryName = "Dinner";
				 }
				 else if (option == 4){//beverages
					 highCal = 100;
					 categoryName = "Beverages";
				 }
				 else if (option == 5){//dessert
					 highCal = 125;
					 categoryName = "Dessert";
				 }
				// checkCal(highCal);
				 insertIntoDB(highCal);
				 updateProgressBar();
				 setExpandableList();
				 updateWhatIate();
			 }
			 
		  class ViewHolder {
			 TextView text;
			 Button low,med,high;
						
			 }
	 }
	
	 @Override
	  public  void onCreate(Bundle savedInstanceState) {
		  di = new DailyInfoDBAdapter1(this);
		 setExpandableList();
		// 	shades1 = new String[1][3];
		// 	shades1[0][0] = "bread  250cal";
		// 	shades1[0][1] = "apple  120cal";
		 //	shades1[0][2] = "banana  75cal";
			super.onCreate(savedInstanceState);
			 try{
			 	db = new ProfileDBAdapter(this);
			 	db.open();
			 	id = db.getId();
			 	System.out.println("id:"+ id);
			 	db.close();
			 }catch (Exception ex){
				 System.out.println("Exception in Custom_ProfileDB");
			 }
			 setContentView(R.layout.foodlist);
			 updateWhatIate();
		     textViewCal = (TextView) findViewById(R.id.TextView05);
			 l1 = (ListView) findViewById(R.id.ListView01);
			 l1.setAdapter(new EfficientAdapter(this));
			 myProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
			 textViewCal = (TextView) findViewById(R.id.TextView06);
			 adv_cat = (Button)findViewById(R.id.advcat);
			 adv_cat.setOnClickListener(new clicker());
			 updateProgressBar();

	 }
	 
	 private List createGroupList() {
		  ArrayList result = new ArrayList();
		  for( int i = 0 ; i < colors.length ; ++i ) {
				HashMap m = new HashMap();
			    m.put( "colorName",colors[i] );
				result.add( m );
			  }
			  return (List)result;
		   }
	 private List createChildList() {
			
			ArrayList result = new ArrayList();
			for( int i = 0 ; i < shades1.length ; i++ ) {
			
		// Second-level lists
			  ArrayList secList = new ArrayList();
			  for( int n = 0 ; n < shades1[i].length ; n += 1 ) {
			    HashMap child = new HashMap();
				child.put( "shadeName", shades1[i][n] );
	//		    child.put( "rgb", shades1[i][n+1] );
			    secList.add( child );
			  }
			  result.add( secList );
		
			}
			return result;
		  }					
 
/*	 public static void insertIntoDB(int caloriesConsumed) {
	       String foodName = "unknown";
		 	int mYear;
	        int mMonth;
	        int mDay;
	        String cal_burned = "0";
	        String calConsumed, userIdString;
	        di.open();    
	        long idl;
	        Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
	        System.out.println("day,month,year " +mYear +mDay +mYear);
	        Date date = convertStringToDate(mDay, mMonth+1, mYear);
	        calConsumed = new Integer(caloriesConsumed).toString();
	        userIdString = new Integer(id).toString();
	        idl = di.insertUserInfo(
	        		userIdString,
	        		categoryName,
	        		foodName,
	        		calConsumed,//Calories_consumed
	        		cal_burned,
	        		date); 
	        	di.close();
		 }*/
	 public static void insertIntoDB(int caloriesConsumed) {
	       String foodName = "unknown";
		 	int mYear;
	        int mMonth;
	        int mDay;
	        String cal_burned = "0";
	        String calConsumed, userIdString;
	        di.open();    
	        long idl;
	        Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
	        System.out.println("day,month,year " +mYear +mDay +mYear);
	        Date date = convertStringToDate(mDay, mMonth+1, mYear);
	        calConsumed = new Integer(caloriesConsumed).toString();
	        userIdString = new Integer(id).toString();
	        idl = di.insertUserInfo(
	        		userIdString,
	        		categoryName,
	        		foodName,
	        		calConsumed,//Calories_consumed
	        		cal_burned,
	        		date); 
	        	di.close();
		 }
		 
		 
	 public static Date convertStringToDate(int date, int month, int year){
         
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
         Date theDate = null;
         String in = date + "/" + month + "/" + year;
         try {
             theDate = dateFormat.parse(in); 
             return theDate;
         } catch (ParseException e) {
             e.printStackTrace();
         }
		 return theDate;
         
     }
		
	 
	 
	 public static void updateProgressBar() {
		 int maximumCal = 3000;
		 int i = Color.RED;

		 int caloriesConsumed = calConsumed();
		 System.out.println("At update progress bar:"+caloriesConsumed);
		 int calConsumePer = (caloriesConsumed * 100)/ maximumCal ;
		 System.out.println("Calories Consumed % " +calConsumePer);
		 try {
		 myProgressBar.setProgress(calConsumePer);
		 myProgressBar.setBackgroundColor(i);
		 String caloriesConsumedText = "CaloriesConsumed: ";
		 caloriesConsumedText = new StringBuffer().append(caloriesConsumedText).append(caloriesConsumed).toString();
		 textViewCal.setText(caloriesConsumedText);
		 }catch(Exception ex){
			 System.out.println(ex.getMessage());
		 }}
		
	 public static int calConsumed(){
		 int calVal = 0;
			try {
				 Calendar c = Calendar.getInstance();
				 int mYear = c.get(Calendar.YEAR);
			     int mMonth = c.get(Calendar.MONTH);
			     int mDay = c.get(Calendar.DAY_OF_MONTH);
			     Date date = convertStringToDate(mDay, mMonth+1, mYear);
				 di.open();
				
		//		 Cursor cur;
			//	 int caloriesConsumed ;
				 calVal = di.getCaloriesConsumedForDay(date);
				 System.out.println("At calConsumed func:"+calVal);
				 di.close();
			} catch (Exception ex){
			 System.out.println("Exception in Custom_ProgressBar");
			}
			return calVal;
	}
			 
	 private  void checkCal(int cal){
		 ctr = ctr +1;
		 totalcal = totalcal +cal;
		 avg = totalcal/ctr;
		 myProgress = 0;
		 while (myProgress< avg){
			 myProgress++;
			 myProgressBar.setProgress(myProgress);	 
		 }
	 }
			 
	 private static final String[] Meal = { "Breakfast", "Lunch", "Snack",
			 "Dinner", "Beverages", "Dessert" };
	
	 public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);

			MenuItem item = menu.add(0, advancedId ,0,R.string.advanced);
			item = menu.add(0, addToProfileId ,0,R.string.addToProfile);
			item = menu.add(0, fitnessId ,0,R.string.fitness);
			return true;
		}
	 
	 
	 public  void updateWhatIate(){
		 try{
			  expListAdapter =
					new SimpleExpandableListAdapter(
						this,
						createGroupList(),	// groupData describes the first-level entries
						R.layout.child_row,	// Layout for the first-level entries
				//		R.layout.child_row1,
						new String[] { "colorName" },	// Key in the groupData maps to display
						new int[] { R.id.childname },
				//		createChildList1(),	// Data under "colorName" key goes into this TextView
						createChildList(),	
				//		R.layout.child_row1,// childData describes second-level entries
				//		new String[]{"shadeName"},
				//		new int[] { R.id.childname}
						
						R.layout.child_row,	// Layout for second-level entries
						new String[] { "shadeName", "rgb" },	// Keys in childData maps to display
						new int[] { R.id.childname, R.id.rgb }	// Data under the keys above go into these TextViews
					);
		//	 expListAdapter.notifyDataSetChanged(); 
			 System.out.println("At ExpanadableList");
				setListAdapter( expListAdapter );
				expListAdapter.notifyDataSetChanged(); 
			 }catch(Exception ex){
				 ex.printStackTrace();
			 }
		 
	 }
	 
	 public void setExpandableList(){
		 	int mDay,mMonth,mYear;
		 	String [] foodList ;
		 	Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
	        System.out.println("day,month,year " +mYear +mDay +mYear);
	        Date date = convertStringToDate(mDay, mMonth+1, mYear);
	        //callWhatIateToday(date);
	//        di = new DailyInfoDBAdapter1(this);
	        di.open();
	        System.out.println("At ONE");
	        foodList = di.getWhatIAteToday(date);
	        System.out.println("At TWO");
	        di.close();
	        System.out.println("At THREE");
	        System.out.println(foodList);
	        int len = foodList.length;
	        shades1 = new String[1][len];
	        for (int v = 0;v <len; v++){
	        	shades1[0][v] = foodList[v];
	        }
		// 	shades1 = new String[1][3];
		// 	shades1[0][0] = "bread  250cal";
		// 	shades1[0][1] = "apple  120cal";
		 //	shades1[0][2] = "banana  75cal";
			
	 }
	 
	  class  clicker implements Button.OnClickListener {  
	//	  @Override;
	    	public void onClick(View v) {
	    		if(v == save){
	    		try{
	    		String cal_burned = "zero";
	    		db.open();
//	    		long result = db.insertDailyInfo(Integer.toString(id),Integer.toString(lowCal),cal_burned,"day","month","year");
	    		db.close();
	    		}catch (Exception ex){
	    			System.out.println("Exception in DailyInfo");
	    		}
	    		}
	    		else if (v == adv_cat){
	    			Intent intent = new Intent(CustomListView.this, AdvCategory.class);
	    			intent.putExtra("id",new Integer(id).toString());
	    	    	 startActivity(intent);
	    		}
	    			
	    	}
	  }	
}
	